#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <map>
#include <sys/wait.h>
#include "client.h"
#include "xmu_ipc.h"
using namespace std;

int sem_flight;
int shm_flight;
class Flights *my_flights;

int main(int argc, char *argv[])
{
    pid_t pid;
    if (argc == 1)
    {
        cout << "Missing arguement, you need to add the file path of input file.";
        return 0;
    }
    // 读取文本文件的每一行
    string input_path(argv[1]);
    vector<string> lines = readLinesFromFile(input_path);

    // 创建信号量和共享内存
    sem_flight = new_sem((char *)"./", 254, 1, 1);
    shm_flight = new_shm((char *)"./", 111, sizeof(class Flights));

    // 将飞机们的信息映射到共享内存空间
    my_flights = (class Flights *)my_shmat(shm_flight);

    // 解析并初始化飞机信息

    my_flights->f_cnt = parseFlights(lines, my_flights->flights_seq);

    // 断开共享内存空间与进程地址空间的关联
    my_shmdt((const void *)my_flights);

    // 解析并初始化代理信息
    vector<Agent> agents = parseAgents(lines);

    auto agent_cnt = agents.size();
    // cout << "agent_cnt" << agents.size(); // debug
    int i, agent_id = 0;
    printf("--------------Begin-----------------\n");

    for (i = 1; i <= agent_cnt; i++)
        if ((pid = fork()) < 0)
        {
            perror("Fork failed");
            exit(0);
        }
        else if (pid == 0) // 子进程;
        {
            agent_id = i;
            break;
        }

    if (agent_id != 0)
    {
        Agent &this_agent = agents[agent_id - 1];
        for (auto op : this_agent.op_seq)
        {
            sem_wait(sem_flight, 0);
            my_flights = (class Flights *)my_shmat(shm_flight);
            my_flights->do_request(op, this_agent.get_time_by_op_name(op.op_func));
            my_shmdt((const void *)my_flights);
            sem_signal(sem_flight, 0);
        }
        exit(agent_id);
    }
    else
    {
        for (int j = 1; j <= agent_cnt; j++)
            wait(NULL);

        my_flights = (class Flights *)my_shmat(shm_flight);
        my_flights->show();
        my_shmdt((const void *)my_flights);
        clear_sem(sem_flight);
        clear_shm(shm_flight);
        printf("--------------End-----------------\n");
    }

    return 0;
}
